import { FrontMatter } from "./frontMatter";
import { Body } from "./body";

export class MarkdownFile {
    private row_content: string='';
    private front_matter: FrontMatter|null;
    private body?: Body|null;
    static DELIMITER = '+++\n';
    constructor(front_matter: FrontMatter, body: Body) {
        this.front_matter = front_matter;
        this.body = body;
    }
    static from(raw_text :string) : MarkdownFile |null {

        const content = raw_text.trimStart();
        if (content.startsWith(MarkdownFile.DELIMITER) === false){
            return null;
        }
        const length = content.split(MarkdownFile.DELIMITER).length
        if (length!== 3) {
            console.log('not 2 delimiter it is ' + length);
            return null;
        }
        const [_,f, b] = content.split(MarkdownFile.DELIMITER);
        const fmObj = FrontMatter.from(f);
        if (fmObj === null) {
            return null;
        }
        const bObj = Body.from(b);
        if (bObj === null) {
            return null;
        }
        const mdFile = new MarkdownFile(fmObj as FrontMatter, bObj as Body);
        mdFile.row_content = content;
        return mdFile;
    }
    public isDraft(): boolean {
        if (this.front_matter === null) {
            return false;
        }
        return this.front_matter.getDraft();
    }
    public getTitle(): string {
        if (this.front_matter === null) {
            return 'unknown';
        }
        return this.front_matter.getTitle();
    }
    public getDate(): string {
        return this.front_matter?.getDate() || 'unknown';
    }
    public getAuthor(): string {
        return this.front_matter?.getAuthor() || 'unknown';
    }
    public to_string(): string {
        return `${MarkdownFile.DELIMITER}${this.front_matter?.to_string()}${MarkdownFile.DELIMITER}${this.body?.to_string()}`;
    }
    public getFrontMatter(): FrontMatter {
        return this.front_matter as FrontMatter;
    }
    public getBody(): Body {
        return this.body as Body;
    }
    public getContent(): string {
        return this.row_content;
    }
}